import cv2
import numpy as np


def imgShreshold():
    image = cv2.imread("E:/4.27.png")  # 读取4.27.png
    image_Gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)  # 将4.27.png转换为灰度图像
    t1, dst1 = cv2.threshold(image_Gray, 127, 255, cv2.THRESH_BINARY)  # 二值化阈值处理
    # 反二值化阈值处理
    t2, dst2 = cv2.threshold(image_Gray, 127, 255, cv2.THRESH_BINARY_INV)
    t3, dst3 = cv2.threshold(image_Gray, 127, 255, cv2.THRESH_TOZERO)  # 低于阈值零处理
    # 超出阈值零处理
    t4, dst4 = cv2.threshold(image_Gray, 127, 255, cv2.THRESH_TOZERO_INV)
    t5, dst5 = cv2.threshold(image_Gray, 127, 255, cv2.THRESH_TRUNC)  # 截断处理
    # 分别显示经过5种阈值类型处理后的图像
    cv2.imshow("BINARY", dst1)
    cv2.imshow("BINARY_INV", dst2)
    cv2.imshow("TOZERO", dst3)
    cv2.imshow("TOZERO_INV", dst4)
    cv2.imshow("TRUNC", dst5)
    cv2.waitKey()  # 按下任何键盘按键后
    cv2.destroyAllWindows()  # 销毁所有窗口

def adaptShreshold():
    image = cv2.imread("E:/4.27.png")  # 读取4.27.png
    image_Gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)  # 将4.27.png转换为灰度图像
    # 自适应阈值的计算方法为cv2.ADAPTIVE_THRESH_MEAN_C
    athdMEAM = cv2.adaptiveThreshold \
        (image_Gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 5, 3)
    # 自适应阈值的计算方法为cv2.ADAPTIVE_THRESH_GAUSSIAN_C
    athdGAUS = cv2.adaptiveThreshold \
        (image_Gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 5, 3)
    # 显示自适应阈值处理的结果
    cv2.imshow("MEAN_C", athdMEAM)
    cv2.imshow("GAUSSIAN_C", athdGAUS)
    cv2.waitKey()  # 按下任何键盘按键后
    cv2.destroyAllWindows()  # 销毁所有窗口


def otsuShreshold():
    image = cv2.imread("E:/4.27.png")  # 读取4.36.jpg
    image_Gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)  # 将4.36.jpg转换为灰度图像
    t1, dst1 = cv2.threshold(image_Gray, 127, 255, cv2.THRESH_BINARY)  # 二值化阈值处理
    # 实现Otsu方法的阈值处理
    t2, dst2 = cv2.threshold(image_Gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
    cv2.putText(dst2, "best threshold: " + str(t2), (0, 30),
                cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 0), 2)  # 在图像上绘制最合适的阈值
    cv2.imshow("BINARY", dst1)  # 显示二值化阈值处理的图像
    cv2.imshow("OTSU", dst2)  # 显示实现Otsu方法的阈值处理
    cv2.waitKey()  # 按下任何键盘按键后
    cv2.destroyAllWindows()  # 销毁所有窗口


if __name__ == '__main__':
    # imgShreshold()
    # adaptShreshold()
    otsuShreshold()